<template>
  <div class="c-dmar8r">
    <NavBar></NavBar>
    <!-- 车船税信息 -->
    <Loading :loading="loading">
      <van-form ref="formInfo">
        <div class="c-91t2s9">
          <!-- <div class="c-91t2s9-title">车船税信息</div>
          <div class="c-91t2s9-list-item">
            <div class="c-8moxqg flex-row flex-align-center">
              <div class="c-8moxqg-item-label">车船税类型</div>
              <div class="c-8moxqg-item-value">
                <van-field
                  class="c-8moxqg-item-value-text"
                  :rules="formRules.carboradTypeRules"
                  :value="carInsuranceInfo.carTaxType"
                  name="carboradType"
                  error-message-align="right"
                  input-align="right"
                  @click="handleVisible('carboradType')"
                >
                  <template #input>
                    <PeoInsured
                      ref="carboradType"
                      title="车船税类型"
                      @confirm="
                        value =>
                          handleConfirm(value, 'carTaxType', carInsuranceInfo)
                      "
                      placeholder="请选择车船税类型"
                      :defaultValue="carInsuranceInfo.carTaxType"
                      :columns="carboradTypeList"
                    />
                  </template>
                </van-field>
              </div>
              <van-icon name="arrow" class="c-8moxqg-item-left" />
            </div>
          </div>

          <div class="c-91t2s9-list-item">
            <div class="c-8moxqg flex-row flex-align-center">
              <div class="c-8moxqg-item-label">金额(元)</div>
              <div class="c-8moxqg-item-value">
                <van-field
                  class="c-8moxqg-item-value-text"
                  v-model="carInsuranceInfo.carTax"
                  name="money"
                  type="number"
                  error-message-align="right"
                  input-align="right"
                  :rules="formRules.moneyRules"
                  placeholder="请填写金额"
                ></van-field>
              </div>
            </div>
          </div> -->
          <div
            class="c-0i1rte-list"
            v-for="(item, index) in riskList"
            :key="index"
          >
            <!-- 交强险/商业险 -->
            <div class="flex-row flex-align-center flex-justify-between">
              <div
                class="c-0i1rte-list-header"
                @click="item.isShow = !item.isShow"
              >
                <van-icon
                  class="c-0i1rte-list-header-icon"
                  name="arrow"
                  v-show="item.isShow"
                />
                <van-icon
                  class="c-0i1rte-list-header-icon"
                  name="arrow-down"
                  v-show="!item.isShow"
                />
                <span class="c-0i1rte-list-header-title">
                  {{ item.riskName }}
                </span>
                
              </div>
            </div>
            <div v-show="!item.isShow">
              <van-cell title="保单号">
                <div class="c-0i1rte-list-item">
                  <van-field
                    class="c-0i1rte-list-item-input"
                    input-align="right"
                    error-message-align="right"
                    
                    v-model="item.carPolicyNo"
                    :rules="formRules.insuranceNoRules"
                    placeholder="请填写保单号"
                  ></van-field>
                </div>
              </van-cell>
              <van-cell title="保费(元)">
                <div class="c-0i1rte-list-item">
                  <van-field
                    class="c-0i1rte-list-item-input"
                    input-align="right"
                    error-message-align="right"
                    type="number"
                    v-model="item.premium"
                    :rules="formRules.moneyRules"
                    placeholder="请填写保费"
                  ></van-field>
                </div>
              </van-cell>
              <van-cell
                title="保险期间"
                is-link
                @click="
                  handleVisible(
                    'insurancePeriodType' + index,
                    index,
                    item.riskId
                  )
                "
              >
                <van-field
                  class="c-0i1rte-list-item-input"
                  input-align="right"
                  v-model="item.insurancePeriodId"
                  :rules="formRules.noEmptyRules"
                >
                  <template #input>
                    <PeoInsured
                      :ref="'insurancePeriodType' + index"
                      title="保险期间类型"
                      @confirm="
                        value =>
                          handleConfirm(
                            value,
                            'insurancePeriodId',
                            riskList,
                            index
                          )
                      "
                      :defaultValue="item.insurancePeriodId"
                      :columns="
                        getDataList(item.riskId).insurancePeriodTypeList
                      "
                    />
                  </template>
                </van-field>
              </van-cell>
              <van-cell
                title="缴费方式"
                is-link
                @click="handleVisible('paymentWay' + index, index, item.riskId)"
              >
                <van-field
                  class="c-0i1rte-list-item-input"
                  input-align="right"
                  v-model="item.paymentWay"
                  :rules="formRules.noEmptyRules"
                >
                  <template #input>
                    <PeoInsured
                      :ref="'paymentWay' + index"
                      title="缴费方式"
                      @confirm="
                        value =>
                          handleConfirm(value, 'paymentWay', riskList, index)
                      "
                      :defaultValue="item.paymentWay"
                      :columns="getDataList(item.riskId).paymentWayList"
                    />
                  </template>
                </van-field>
              </van-cell>
              <van-cell
                title="缴费年期"
                is-link
                @click="
                  handleVisible('payPeriodId' + index, index, item.riskId)
                "
              >
                <van-field
                  class="c-0i1rte-list-item-input"
                  input-align="right"
                  v-model="item.payPeriodId"
                  :rules="formRules.noEmptyRules"
                >
                  <template #input>
                    <PeoInsured
                      :ref="'payPeriodId' + index"
                      title="缴费年期"
                      @confirm="
                        value =>
                          handleConfirm(value, 'payPeriodId', riskList, index)
                      "
                      :defaultValue="item.payPeriodId"
                      :columns="getDataList(item.riskId).payPeriodTypeList"
                    />
                  </template>
                </van-field>
              </van-cell>
              <van-cell
                title="被保人"
                is-link
                @click="handleVisible('partIds' + index, index, item.riskId)"
              >
                <van-field
                  class="c-0i1rte-list-item-input"
                  input-align="right"
                  type="number"
                  :value="item.partId"
                  :rules="formRules.noEmptyRules"
                >
                  <template #input>
                    <PeoInsured
                      :ref="'partIds' + index"
                      title="被保人"
                      @confirm="
                        value => {
                          handleConfirm(value, 'partId', riskList, index)
                          handleConfirm(value, 'partIds', riskList, index)
                        }
                      "
                      :defaultValue="item.partIds"
                      :columns="getDataList(item.riskId).peopleList"
                    />
                  </template>
                </van-field>
              </van-cell>
              <van-cell
                title="车船税类型"
                is-link
                @click="handleVisible('carboradType' + index, index, item.riskId)"
              >
                <van-field
                  class="c-0i1rte-list-item-input"
                  :rules="formRules.carboradTypeRules"
                  v-model="item.carTaxType"
                  name="carboradType"
                  error-message-align="right"
                  input-align="right"
                  
                >
                  <template #input>
                    <PeoInsured
                      :ref="'carboradType' + index"
                      title="车船税类型"
                      @confirm="
                        value =>
                          handleConfirm(value, 'carTaxType', riskList, index)
                      "
                      :defaultValue="item.carTaxType"
                      :columns="carboradTypeList"
                    />
                  </template>
                </van-field>
              </van-cell>
              <van-cell title="金额(元)">
                <div class="c-0i1rte-list-item">
                  <van-field
                    class="c-0i1rte-list-item-input"
                    input-align="right"
                    error-message-align="right"
                    type="number"
                    v-model="item.carTax"
                    :rules="formRules.moneyRules"
                    placeholder="请填写金额"
                  ></van-field>
                </div>
              </van-cell>
            </div>
          </div>
        </div>
      </van-form>
      <div>
        <div class="c-0i1rte-bottom-next" @click="handleMenu">下一步</div>
      </div>
    </Loading>
  </div>
</template>
<script>
import NavBar from '@/components/h5header'
import PeoInsured from '@/components/peoInsured'
import { mapMutations, mapGetters, mapState, mapActions } from 'vuex'
import comAPI from '@/services/h5/common'
import API from '@/services/h5/product'
import Loading from '@/components/data-loading'
export default {
  components: { NavBar, PeoInsured, Loading },
  computed: {
    ...mapGetters('common', ['formRules']),
    ...mapState('carProduct', ['riskList', 'carInsuranceInfo']),
    ...mapState('loading', ['loading'])
  },
  data() {
    return {
      iscarThree: false,
      carboradTypeList: [],
      riskTypeList: [],
      riskShow:false,
      riskResMap: [],
      // itemChild1 : {},
      // itemChild2 : {},
      itemChild1Flag:undefined,
      itemChild2Flag:undefined
    }
  },
  created() {
    this.init()
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (from.path !== '/carThree') {
        vm.iscarThree = false
      } else {
        vm.iscarThree = true
      }
    })
  },
  methods: {
    ...mapMutations('loading', ['setLoading']),
    ...mapMutations('carProduct', ['setRiskList', 'setCarInsuranceInfo']),
    ...mapActions('carProduct', ['getProductDetailInfo']),
    async init() {
      this.setLoading(true)
      this.getProductDetailInfo({
        contractId: this.$route.query.contractId
      })
      // 获取所需要的字典值，性别/证件类型/银行卡类型/国籍/与投保人的关系/婚姻状况
      let res = await Promise.all([
        comAPI.getDictList({
          codeType: 'carTaxType'
        })
      ])
      this.carboradTypeList = res[0].data.data
      //获取险种信息
      let riskRes = await API.getRiskQuery({
        contractId: this.$route.query.contractId
      })
      this.riskResMap = riskRes
      // console.log('sjaksdhajksdhj:',riskRes)
      if (riskRes.data.code === 1000) {
        let rule = {
          riskId: 'code',
          riskName: 'codeName'
        }
        this.riskTypeList = this.changeProp(rule, riskRes.data.data)
        // this.setRiskDataList(riskRes.data.data)
        this.setLoading(false)
      }
    },
    setRiskDataList(res) {
      let result = []
      let data = this.riskList.length === 0 ? res : this.riskList
      data.forEach(item => {
        let obj = {
          isShow: false,
          riskId: item.riskId,
          riskName: item.riskName,
          insurancePeriodId: item.insurancePeriodId
            ? item.insurancePeriodId
            : '',
          payPeriodId: item.payPeriodId ? item.payPeriodId : '',
          paymentWay: item.paymentWay ? item.paymentWay : '',
          premium: item.premium ? item.premium : '',
          partIds: item.partIds ? item.partIds : '',
          prFlag: item.prFlag,
          partId: item.partId ? item.partId : '',
          carPolicyNo: item.carPolicyNo ? item.carPolicyNo : '',
          sumAssured: 0
        }
        result.push(obj)
      })
      this.setRiskList(result)
    },
    async handleMenu() {
      // console.log('this.riskList',this.riskList)
      this.itemChild1Flag = true
      this.itemChild2Flag = true
      let itemChild2 = {}
      let itemChild1 = {}
      let params = {
        contractId: this.$route.query.contractId,
        risks: this.riskList.map(
          ({
            premium,
            riskId,
            carPolicyNo,
            insurancePeriodId,
            partId,
            payPeriodId,
            paymentWay,
            carTax,
            carTaxType
          }) => {
            return {
              premium,
              riskId,
              carPolicyNo,
              insurancePeriodId,
              partIds: [partId],
              payPeriodId,
              payWayId: paymentWay,
              sumAssured: 0,
              carTax,
              carTaxType
            }
          }
        )
      }
      // console.log('提交前params:',params)
      params.risks.forEach((item,index) => {
        if(index == 0) {
          if(item.carTaxType==""){
            item.carTax=0
          }
          itemChild1 = JSON.parse(JSON.stringify(item))
          delete itemChild1.sumAssured
          delete itemChild1.riskId 
        }
        if(index == 1) {
          if(item.carTaxType=="2"){
            item.carTax=0
          }
          itemChild2 = JSON.parse(JSON.stringify(item))
          delete itemChild2.sumAssured
          delete itemChild2.riskId
        }
      })
      Object.values(itemChild1).some(item => {
        if(!String(item)) {
          this.itemChild1Flag = false
          return true
        }
      })
      Object.values(itemChild2).some(item => {
        if(!String(item)) {
          this.itemChild2Flag = false
          return true
        }
      })
      params.risks.forEach(item => {
        if(item.premium=='') {
          item.premium = 0
        }
      })
      if(!this.itemChild1Flag&&!this.itemChild1Flag) {
        this.$message.error('请完整填写其中一个险种信息')
        return
      }
      if(this.itemChild1Flag||this.itemChild2Flag) {
        let count1 = 0 
        let count2 = 0
        Object.values(itemChild1).some(item => {
          if(String(item)){
            count1++
          }
        })
        Object.values(itemChild2).some(item => {
          if(String(item)){
            count2++
          }
        })
        if( 0 < count1 && count1 < 8) {
          this.$message.error('险种信息未填写完整，请检查填写')
          return 
        }
        if( 0 < count2 && count2 < 8) {
          this.$message.error('险种信息未填写完整，请检查填写')
          return 
        }
        console.log('23提交了')
        let res = await API.saveRiskInfo(params)
        if (res.data && res.data.code === 1000) {
          let path = `/carThree`
          this.$router.push({
            path,
            query: {
              contractId: this.$route.query.contractId
            }
          })
        }
      }
      
      /* this.$refs.formInfo
        .validate()
        .then(async () => {
          let params = {
            contractId: this.$route.query.contractId,
            // carTaxType: this.carInsuranceInfo.carTaxType,
            // carTax: this.carInsuranceInfo.carTax,
            risks: this.riskList.map(
              ({
                premium,
                riskId,
                carPolicyNo,
                insurancePeriodId,
                partId,
                payPeriodId,
                paymentWay,
                carTax,
                carTaxType
              }) => {
                return {
                  premium,
                  riskId,
                  carPolicyNo,
                  insurancePeriodId,
                  partIds: [partId],
                  payPeriodId,
                  payWayId: paymentWay,
                  sumAssured: 0,
                  carTax,
                  carTaxType
                }
              }
            )
          }
          let res = await API.saveRiskInfo(params)
          if (res.data && res.data.code === 1000) {
            let path = `/carThree`
            this.$router.push({
              path,
              query: {
                contractId: this.$route.query.contractId
              }
            })
          }
        })
        .catch(() => {}) */
    },
    handleVisible(type, index) {
      // console.log('dadafdafafda', type, index, this.$refs[type])
      if (index !== undefined) {
        this.$refs[type][0].visible = true
      } else {
        this.$refs[type].visible = true
      }
    },
    // 各个类型的选择
    handleConfirm(value, prop, data, index) {
      // console.log('ddddd', value, prop, data, index)
      let flag = index !== undefined
      if (flag) {
        data[index][prop] = value
      } else {
        data[prop] = value
      }
      this.setCarInsuranceInfo([prop, value])
    },
    changeProp(rule, data) {
      let result = []
      data.map(item => {
        let obj = {}
        for (let i in rule) {
          obj[rule[i]] = item[i]
        }
        result.push({
          ...obj,
          ...item
        })
      })
      return result
    },
    getDataList(riskId) {
      const value = this.riskTypeList.find(item => item.riskId == riskId)
      // 被保人
      let rule1 = {
        id: 'code',
        insurancePeriod: 'codeName'
      }
      let rule2 = {
        id: 'code',
        payWay: 'codeName'
      }
      let rule3 = {
        id: 'code',
        paymentPeriod: 'codeName'
      }
      let rule4 = {
        partId: 'code',
        name: 'codeName'
      }
      if (!value) {
        return {
          insurancePeriodTypeList: [],
          paymentWayList: [],
          payPeriodTypeList: [],
          peopleList: []
        }
      } else {
        return {
          insurancePeriodTypeList: this.changeProp(
            rule1,
            value.insurancePeriods
          ),
          paymentWayList: this.changeProp(rule2, value.payWays),
          payPeriodTypeList: this.changeProp(rule3, value.payPeriods),
          peopleList: this.changeProp(rule4, value.parts)
        }
      }
    }
  }
}
</script>
<style scoped lang="less">
.c-dmar8r {
  border: 1px solid transparent;
  box-sizing: border-box;
}
.c-91t2s9 {
  margin-top: 13px;
  padding: 15px;
  background: #fff;
  &-title {
    font-size: 19px;
    font-weight: bold;
    color: #000;
  }
  &-title-plus {
    color: @c-color-primary;
    font-size: 15px;
  }
  &-list {
    margin-top: 15px;
    box-shadow: rgba(0, 0, 0, 0.07) 0 0 10px 0;
    padding: 0 15px;
    &-title {
      padding: 5px 0;
      font-size: 18px;
    }
    &-del {
      font-size: 15px;
      color: @c-color-primary;
      flex-direction: row-reverse;
    }
  }
  &-list-item {
    border-bottom: 0.5px solid #e9e9e9;
  }
}
.c-8moxqg-item {
  &-label {
    width: 60px;
    font-size: 15px;
    color: #333;
    text-align: justify;
    text-align-last: justify;
  }
  &-value {
    flex: 1;
    /deep/.van-field--error .van-field__control::placeholder {
      color: #999;
    }
  }
  &-value-text {
    font-size: 15px;
    color: #333;
    text-align: left;
  }
  &-margin-left {
    margin-left: 15px;
  }
  &-value-text-active {
    /deep/.van-field__control:disabled {
      color: #333;
      -webkit-text-fill-color: #333;
    }
  }
  &-left {
    font-size: 16px;
    color: #999;
  }
  &-img {
    width: 15px;
    height: 15px;
  }
  &-scan {
    color: @c-color-primary;
    font-size: 16px;
    margin-right: 3px;
  }
  &-img-text {
    font-size: 14px;
    color: @c-color-primary;
  }
}
.c-0i1rte {
  &-list {
    &-header {
      &-icon {
        font-size: 15px;
      }
      &-title {
        font-size: 16px;
        font-weight: bold;
      }
      &-add,
      &-del {
        background: @c-color-primary;
        padding: 2px 10px;
        color: #fff;
        font-size: 14px;
        border-radius: 10px;
      }
      &-add {
        margin-top: 15px;
        height: 40px;
        line-height: 40px;
      }
    }
    &-item {
      /deep/.van-field--error .van-field__control::placeholder,
      /deep/.van-field--error .van-field__control {
        color: #999;
      }
      &-input {
        padding: 0;
      }
    }
  }
  &-bottom-next {
    width: 345px;
    margin-left: 15px;
    height: 50px;
    line-height: 50px;
    background: @c-color-primary;
    border-radius: 10px;
    color: #fff;
    text-align: center;
    font-size: 16px;
    margin-bottom: 15px;
  }
}
</style>
